<template>
  <div>
    <el-row>
      <el-col :span="24">
        <div class="search-box">
          <!-- <el-form :inline="true" size="medium">
            <el-form-item>
              <el-button type="primary" @click="showAddDialogForm">新增</el-button>
            </el-form-item>
          </el-form> -->

          <el-form :inline="true" size="medium" :model="searchForm">
            <el-form-item>
              <el-button type="primary" size="mini" @click="exportExcel">Excel导出</el-button>
            </el-form-item>
            <el-form-item label="姓">
              <el-input v-model="searchForm.surname" clearable placeholder="姓"></el-input>
            </el-form-item>

            <el-form-item label="名">
              <el-input v-model="searchForm.name" clearable placeholder="名"></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" size="mini" @click="search">查询</el-button>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" size="mini" @click="search">刷新</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>

    <el-table
      :data="tableData"
      :header-cell-style="{backgroundColor:'#f4f4f5',textAlign:'center'}"
      :cell-style="{textAlign:'center'}"
      :height="tableHeight"
      border
      style="width: 100%">

      <el-table-column
        prop="id"
        label="序号"
        type="index"
        width="80">
      </el-table-column>

      <el-table-column
        prop="name"
        label="姓名"
        min-width="120">
        <template scope="scope">
          {{userName(scope.row.name,scope.row.surname)}}
        </template>
      </el-table-column>
      <el-table-column
        prop="gender"
        label="性别"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="idNumber"
        label="证件号"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="phone"
        label="电话"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="emergencyContact"
        label="紧急联系人"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="contactWay"
        label="联系方式"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="comeFrom"
        label="来地"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="whereToGo"
        label="目的地"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="allergen"
        label="食物过敏情况"
        min-width="120">
      </el-table-column>


      <el-table-column
        prop="note"
        label="备注"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="invoice"
        label="是否开发票"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="invoiceType"
        label="发票类型"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="invoiceUp"
        label="发票抬头"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="invoiceNumber"
        label="税号"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="location"
        label="注册地址"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="invoicePhone"
        label="注册电话"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="invoiceBank"
        label="注册银行"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="invoiceAccount"
        label="账号"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="录入时间"
        min-width="120">
        <template scope="scope">
          {{fmtDate(scope.row.createTime)}}
        </template>
      </el-table-column>


      <!-- <el-table-column
        prop="offDutyTime"
        label="下班时间"
        min-width="120">
        <template scope="scope">
          {{dateFormatter(scope.row.offDutyTime)}}
        </template>
      </el-table-column> -->

      <el-table-column
        prop="address"
        fixed="right"
        label="操作"
        min-width="250">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="showFile(scope.$index, scope.row)">显示身份证</el-button>
          <el-button style="margin-left:4px" size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button style="margin-top:8px" size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
       <span class="demonstration"></span>
       <el-pagination
         @size-change="handleSizeChange"
         @current-change="handleCurrentChange"
         :current-page="currentPage"
         :page-sizes="[10, 20, 50, 100,200]"
         :page-size="pageSize"
         layout="total, sizes, prev, pager, next, jumper"
         :total="total">
       </el-pagination>
     </div>

    <el-dialog :title="editForm.id==0?'新增':'修改'" :visible.sync="editFormVisible" width="500px" :close-on-click-modal="false">
      <el-form :model="editForm" ref="editForm" :rules="editRules">

        <el-form-item label="姓" label-width="100px" prop="surname">
          <el-input v-model="editForm.surname" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="名" label-width="100px" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>


        <el-form-item label="性别" label-width="100px" prop="gender">
          <el-select v-model="editForm.gender"  placeholder="请选性别" clearable>
            <el-option :key="1" label="男" :value="1"></el-option>
            <el-option :key="2" label="女" :value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="证件号" label-width="100px" prop="idNumber">
          <el-input v-model="editForm.idNumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" label-width="100px" prop="phone">
          <el-input v-model="editForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="紧急联系人" label-width="100px" prop="emergencyContact">
          <el-input v-model="editForm.emergencyContact" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" label-width="100px" prop="contactWay">
          <el-input v-model="editForm.contactWay" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="来地" label-width="100px" prop="comeFrom">
          <el-input v-model="editForm.comeFrom" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="目的地" label-width="100px" prop="whereToGo">
          <el-input v-model="editForm.whereToGo" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="食物过敏情况" label-width="100px" prop="allergen">
          <el-input v-model="editForm.allergen" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" label-width="100px" prop="note">
          <el-input v-model="editForm.note" autocomplete="off"></el-input>
        </el-form-item>


        <el-form-item label="是否开发票" label-width="100px" prop="invoice">
          <el-select v-model="editForm.invoice"  placeholder="请选择" clearable>
            <el-option :key="1" label="是" :value="'是'"></el-option>
            <el-option :key="2" label="否" :value="'否'"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发票类型" label-width="100px" prop="invoiceType" clearable v-if="editForm.invoice=='是'">
          <el-select v-model="editForm.invoiceType"  placeholder="请选择" >
            <el-option :key="1" label="纸质发票" :value="'纸质发票'"></el-option>
            <el-option :key="2" label="电子发票" :value="'电子发票'"></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="发票抬头" label-width="100px" prop="invoiceUp" clearable v-if="editForm.invoice=='是'">
          <el-input v-model="editForm.invoiceUp" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="税号" label-width="100px" prop="invoiceNumber" clearable v-if="editForm.invoice=='是'">
          <el-input v-model="editForm.invoiceNumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="注册地址" label-width="100px" prop="location" clearable v-if="editForm.invoice=='是'">
          <el-input v-model="editForm.location" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="注册电话" label-width="100px" prop="invoicePhone" clearable v-if="editForm.invoice=='是'">
          <el-input v-model="editForm.invoicePhone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="注册银行" label-width="100px" prop="invoiceBank" clearable v-if="editForm.invoice=='是'">
          <el-input v-model="editForm.invoiceBank" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="账号" label-width="100px" prop="invoiceAccount" clearable v-if="editForm.invoice=='是'">
          <el-input v-model="editForm.invoiceAccount" autocomplete="off"></el-input>
        </el-form-item>




      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click.native.prevent="submitForm" :loading="loading">{{ editForm.id==0?'添 加':'修 改' }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="imgDialogVisible" width="650px">
      <div style="display: flex;flex-direction: column;justify-content: center;align-items: center;">

      <template v-for="(item,index) in photos">
        <el-image
            style="width: 500px;margin-top: 8px;"
            :src="fileBaseUrl + item"
            :preview-src-list="[fileBaseUrl + item]"
            v-if="!isVideo(item)">
          </el-image>
      </template>

      </div>
    </el-dialog>

  </div>
</template>

<script>
import {validPhone} from '@/common/utils/validate.js'
import request from '@/common/utils/request.js'
import util from '@/common/utils/util.js'
import {getGoEpidemicRegisterList ,deleteGoEpidemicRegister,updateGoEpidemicRegister} from "@/api/go_epidemic_register.js";
import {getTestUserList} from "../../../api/test_workload.js";
import {getToken} from "../../../common/utils/auth";
import axios from "axios";

export default {
  name: "goEpidemicRegister",
  data() {
    return {
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableData: [],
      tableHeight: 200,
      editFormVisible:false,
      loading: false,
      url:'',

      photos:[],
      TestUserList:[],

      editForm: {
        id: 0,
        name: '',
        surname: '',
        gender: '',
        idNumber: '',
        phone: '',
        emergencyContact: '',
        contactWay: '',
        comeFrom: '',
        whereToGo: '',
        allergen: '',
        note: '',
        invoice: '',
        invoiceType: '',
        invoiceUp: '',
        invoiceNumber: '',
        location: '',
        invoicePhone: '',
        invoiceBank: '',
        invoiceAccount: '',



        beOnDutyTime: new Date(2022, 9, 10, 18, 40),
        offDutyTime: new Date(2022, 9, 10, 18, 40),
      },
      editRules: {
        serialNumber: [{ required: true, message:"请输入编号", trigger: 'blur'}],
        name: [{ required: true, message:"请输入名称", trigger: 'blur'}],
        classesResponsible: [{ required: true, message:"请输入班次负责人", trigger: 'blur'}],
        beOnDutyTime: [{ required: true, message:"请输入上班时间", trigger: 'blur'}],
        offDutyTime: [{ required: true, message:"请输入下班时间", trigger: 'blur'}],
      },
      loadingDiv: null,
      searchForm: {
        surname:'',
        name:'',
      },

      imgDialogVisible:false,
    }
  },
  watch:{

  },
  mounted() {
    let t = getToken();
    this.uploadActionUrl = this.$adminApiUrl + "/file/upload?_t="+t;
    this.fileBaseUrl = this.$adminApiUrl+"/file/gets?_t="+t+"&f=";


    this.getDataList(this.currentPage);

    this.$nextTick(() => {
        this.tableHeight = document.documentElement.clientHeight - 198;
    })
    window.onresize = () => {
      this.$nextTick(() => {
          this.tableHeight = document.documentElement.clientHeight - 198;
      })
    }
  },
  methods: {

    isVideo(val){
      if(util.isEmpty(val)){
        return false;
      }
      if(val.toLowerCase().indexOf(".avi") != -1 || val.toLowerCase().indexOf(".mp4") != -1){
        return true;
      }
      return false;
    },

    showFile(index,row){
      // console.log(row)
      if(util.isEmpty(row.idCard)&&util.isEmpty(row.idCardReverseSide)){
        this.$message.error("用户未上传");
        return;
      }
      this.photos = [];
      this.photos.push(row.idCard);
      this.photos.push(row.idCardReverseSide);
      // console.log(this.photos)
      // for(var i=0;i<this.photos.length;i++){
      //   axios.get(this.fileBaseUrl+this.photos[i])
      //           .then((response) =>{
      //           this.url = response.data;
      //           });
      // }
      // console.log(this.url)
      this.imgDialogVisible = true;
    },


    exportExcel(){
      const loadingDiv = util.showLoading("正在导出EXCEL")

      let param = {};
      // console.log(param);

      let t = getToken();
      let headers = {"x-token": t};
      axios({
        method: 'post',
        url: this.$adminApiUrl + "/go-epidemic-register/excel-export", // 请求地址
        data: param, // 参数
        headers: headers,
        responseType: 'blob' ,// 表明返回服务器返回的数据类型

      }).then(res=>{
        loadingDiv.close();
        let blob = new Blob([res.data], { type: 'application/xlsx' })
        let url = window.URL.createObjectURL(blob)
        const link = document.createElement('a') // 创建a标签
        link.href = url;
        let timeStr = "";//this.fmtDate(new Date(),"yyyyMMdd_hhmmss");
        link.download = '疫情填报信息' + '.xlsx' // 重命名文件
        link.click()
        URL.revokeObjectURL(url)

      }).catch(err=>{
        console.log(err);
        loadingDiv.close();
        this.$alert("导出失败,请检查网络", {dangerouslyUseHTMLString:true,type:'warning'})
      });
    },

    showAddDialogForm() {
      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }
      this.editForm.id = 0
      this.editForm.name = "";
      this.editForm.serialNumber = "";
      this.editForm.classesResponsible = "";
      this.editForm.beOnDutyTime = "";
      this.editForm.offDutyTime = "";
      this.editFormVisible = true;
    },

    handleEdit(index, row) {

      if(this.$refs.editForm){
        this.$refs.editForm.clearValidate();
      }
      this.editForm.id = row.id;
      this.editForm.name = row.name;
      this.editForm.gender = row.gender;
      this.editForm.phone = row.phone;
      this.editForm.idNumber = row.idNumber;
      this.editForm.emergencyContact = row.emergencyContact;
      this.editForm.contactWay = row.contactWay;
      this.editForm.comeFrom = row.comeFrom;
      this.editForm.whereToGo = row.whereToGo;
      this.editForm.allergen = row.allergen;
      this.editForm.note = row.note;
      this.editForm.invoice = row.invoice;
      this.editForm.invoiceType = row.invoiceType;
      this.editForm.invoiceUp = row.invoiceUp;
      this.editForm.invoiceNumber = row.invoiceNumber;
      this.editForm.location = row.location;
      this.editForm.invoicePhone = row.invoicePhone;
      this.editForm.invoiceBank = row.invoiceBank;
      this.editForm.invoiceAccount = row.invoiceAccount;
      this.editForm.surname = row.surname;



      this.editFormVisible = true;

    },
    fmtDate(d2, fmt) { // yyyy-MM-dd hh:mm:ss
      if (util.isEmpty(d2) || d2 <= 0){
        return "";
      }
      return  util.fmtDate(new Date(d2), fmt);
    },

    userName(name,surname){
      if(surname==null){
        return name;
      }
      return surname+name;
    },

    format(time, format) {
                    var t = new Date(time);
                    var tf = function (i) { return (i < 10 ? '0' : '') + i };
                    return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {
                        switch (a) {
                            case 'yyyy':
                                return tf(t.getFullYear());
                                break;
                            case 'MM':
                                return tf(t.getMonth() + 1);
                                break;
                            case 'mm':
                                return tf(t.getMinutes());
                                break;
                            case 'dd':
                                return tf(t.getDate());
                                break;
                            case 'HH':
                                return tf(t.getHours());
                                break;
                            case 'ss':
                                return tf(t.getSeconds());
                                break;
                        }
                    })
                },
      dateFormatter(row, column) {
      			var t = new Date(row);
      				return this.format(t,'HH:mm:ss');


      		},


    submitForm() {
      this.$refs.editForm.validate(valid => {
        if(valid) {
          this.loading = true;
          let loadingText = "添加中...";
          if(this.editForm.id){
            loadingText = "修改中...";
          }
          const loadingDiv = util.showLoading(loadingText)
          let func = updateGoEpidemicRegister
          if(this.editForm.id == 0){
            func = addGoClasses
          }
          func(this.editForm).then(res => {
            let title = "修改"
            if(this.editForm.id == 0){
              title = "添加"
            }
            if(res.code == 0) {
              this.$alert(res.msg, title+"失败", {dangerouslyUseHTMLString:true,type:'warning'})
            }else if(res.code == 1) {
              this.$alert(res.msg, title+"成功", {dangerouslyUseHTMLString:true,type:'success'})
                .then(()=> {
                  this.editFormVisible=false;
                  this.getDataList(this.currentPage)
                })
            }
            this.loading = false;
            loadingDiv.close();
          }).catch(res => {
            this.loading = false;
            loadingDiv.close();
          })
        }
      });
    },
    handleDelete(index, row) {
      let loadingDiv;
      this.$confirm("是否确认删除："+row.name+"?","删除确认").then(res=>{
        if(res='confirm'){
          loadingDiv = util.showLoading("删除中...")
          return deleteGoEpidemicRegister({id: row.id})
        }
      }).then(res => {
        loadingDiv.close();
        if(res.code == 0) {
          this.$alert(res.msg, "删除失败", {dangerouslyUseHTMLString:true,type:'warning'})
        }else if(res.code == 1) {
          this.$alert(res.msg, "删除成功", {dangerouslyUseHTMLString:true,type:'success'})
            .then(res=>{
              this.editFormVisible=false;
              this.getDataList(this.currentPage)
            })
        }
      }).catch(res=>{
        if (loadingDiv){
          loadingDiv.close();
        }
      })
    },
    getDataList(pageNum){
      const loadingDiv = util.showLoading()

      getGoEpidemicRegisterList({
        pageSize: this.pageSize,
        pageNum: pageNum,
        surname: this.searchForm.surname,
        name: this.searchForm.name,
      }).then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
          let data = res.data;
          this.currentPage = pageNum;
          this.total = data.total;
          this.tableData = data.dataList;
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })

      getTestUserList().then(res => {
        if(res.code == 0) {
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'error'
          });
        }else if(res.code == 1) {
           this.TestUserList = res.data;
        }
        loadingDiv.close();
      }).catch(res => {
        loadingDiv.close();
      })
    },
    search() {
      this.getDataList(this.currentPage)
    },
    handleSizeChange(pageSize) {
            this.pageSize = pageSize;
            this.getDataList(1)
          },
    handleCurrentChange(pageNum) {
            this.getDataList(pageNum);
          },
  }
}
</script>

<style scoped lang="scss">
  // @import "~@/common/styles/element-variables.scss";
  .search-box {
    background-color: #FFFFFF;
    min-height: 36px;
    line-height: 36px;
    padding-top: 2px;
    padding-bottom: 6px;
    .el-form-item {
      margin-bottom: 0px !important;
    }
    .el-form--inline {
      display: inline-block;
    }
  }
  .pagination-box {
    text-align: left;
    margin-top: 10px;
  }
</style>
<style lang="scss">
  .el-dialog__header {

  }
  .el-dialog__body {
    padding-top: 10px;
    padding-bottom: 0px;
  }
  .el-dialog__footer {
    padding-top: 0px;
  }
</style>
